package dk.peterbn.intervaltrainer.model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The model representation of an interval
 *
 * @author peter
 */
public class Interval {

    //Just use seconds for internal representation
    private int seconds;
    private final String description;
    public static final Pattern LINE_PATTERN = Pattern.compile("(\\d+):([012345]?\\d)(.*)");

    public Interval(int seconds, String description) {
        this.seconds = seconds;
        this.description = description;
    }

    @Override
    public String toString() {
        return getTimeString() + " " + description;
    }

    public int getSeconds() {
        return seconds;
    }

    public String getDescription() {
        return description;
    }

    public String getTimeString() {
        return String.format("%02d:%02d", getMinutesPart(), getSecondsPart());
    }

    public int getSecondsPart() {
        return seconds % 60;
    }

    public int getMinutesPart() {
        return seconds / 60;
    }



    /**
     * Parse a line from the training program file
     * @param line The line to parse
     * @return The interval representing the line, or <code>null</code> if the line is unparsable
     */
    public static Interval parse(String line) {
        Matcher matcher = LINE_PATTERN.matcher(line);
        if (matcher.matches()) {
            String minuteString = matcher.group(1);
            String secondString = matcher.group(2);
            String description = matcher.group(3);
            int minutes = Integer.parseInt(minuteString);
            int seconds = Integer.parseInt(secondString);
            if (description != null) {
                description = description.trim();
            }
            return new Interval(minutes * 60 + seconds, description);
        }
        return null;
    }

    public long getDelayMilis() {
        return seconds * 1000;
    }
}
